
const model = require('../schems')




let categoryAction = {}
// 增加分类
categoryAction.add = function(obj,callback){
  model.category.find({},function(err,result){
    if(result){
      obj.cateid = result.length+1
      let category = model.category(obj)
      category.save().then(e=>callback(e))
    }
  })

  
}

//所有分类
categoryAction.all = function(callback){
  model.category.find({},function(err,result){
    if(result){
      callback(result)
    }
  })
}

//根据id查询
categoryAction.getByid=async function(cateid,callback){
  let allcate,curentcate,arctile;
  await  model.category.find({},function(err,result){
    if(result){
      allcate = result
    }
  })

 await model.category.findOne({cateid},function(err,result){
    if(result){
      curentcate =result
    }
  })
  await callback(allcate,curentcate,arctile)
}

//根据id更新
categoryAction.updateByid=async function(cateid,cate,callback){
  await  model.category.updateOne({cateid},cate,function(err,result){
    if(result){
     callback(true)
    }
  })  
}

//根据id删除
categoryAction.deleteByid =async function(cateid,callback){
  await  model.category.deleteOne({
    cateid },function(err){
      if(!err){
        callback(true)
        console.log('删除成功')
      }
    })
}

//根据分类查询文章
categoryAction.allActile = async function(cateid,callback){
  let categoryId
 await model.category.findOne({cateid},function(err,result){
   console.log('objectid',result)
    categoryId = result._id
  })
await   model.article.find({categoryId}).populate('authorId','name').populate('categoryId').exec(function(err, doc){
  if(doc.length ==0){
    callback(false)
  }else{
    callback(doc)
  }
  //console.log('获得查询结果',doc);
  
})
}

module.exports = categoryAction